package cn.kgc.springmvc.controller;

import cn.kgc.springmvc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/2/29
 * @description
 *
 * 在类中定义的方法上添加 @ExceptionHandler注解后  在类中出现异常之后
 * 会自动进行方法的调用  但是该方式只对当前类中异常有效    局部异常处理方案
 *
 */
@Controller
@RequestMapping("user")
public class UserController {

    // @RequestMapping("toLogin")
    // public String toLogin() {
    //
    //     return "login";
    // }


    @RequestMapping("login")
    public String login(String username, String password, HttpSession session) {

        if ("root".equals(username)&&"123456".equals(password)){
            // 标识用户的登录状态
            session.setAttribute("username",username);
            return "main";
        }else {
            session.setAttribute("info","用户名或密码错误");
            return "redirect:/login.jsp";
        }

    }

    @RequestMapping("add")
    @ResponseBody
    public Map<String,Object> addUser(User user) {

        System.out.println("user = " + user);
        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("code",0);
        result.put("message","添加成功");
        return result ;
    }


    @RequestMapping("delete")
    @ResponseBody
    public Map<String,Object> deleteUser(Integer id) {


        if (id<0){
            throw  new RuntimeException("参数异常");
        }

        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("code",0);
        result.put("message","删除成功"+id);


        return result ;
    }


    @RequestMapping("update")
    @ResponseBody
    public Map<String,Object> updateUser(User user) {

        int a = 1/0;

        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("code",0);
        result.put("message","修改成功");

        return result ;
    }


    // 自定义方法  用于处理当前类中的异常
    // @ExceptionHandler(Exception.class)
    // @ResponseBody
    // public  Map<String,Object>  exceptionHandler(Exception e){
    //     System.out.println(e.getMessage());
    //     e.printStackTrace();
    //     HashMap<String, Object> result = new HashMap<String, Object>();
    //     result.put("code",500);
    //     result.put("message","服务器繁忙,请稍后再试");
    //
    //     return result;
    // }
    //
    // @ExceptionHandler({ArithmeticException.class, NullPointerException.class})
    // @ResponseBody
    // public  Map<String,Object>  arithmeticExceptionHandler(Exception e){
    //
    //     HashMap<String, Object> result = new HashMap<String, Object>();
    //     result.put("code",500);
    //     result.put("message","数学运算异常");
    //     return result;
    // }



}
